#ifndef CYDEVICE_H
#define CYDEVICE_H

#include <QObject>
#include <QQueue>
#include <QtCore>
#include <Windows.h>
#include <CyAPI.h>

struct ReceiveData {
	uchar* data;
	int height;
	int width;
	ReceiveData()
		: ReceiveData(nullptr, 0, 0) {}
	ReceiveData(uchar* data, int width)
		: ReceiveData(data, 1, width) {}
	ReceiveData(uchar* data, int height, int width)
		: data(data), height(height), width(width) {}
	ReceiveData copy() const
	{
		ReceiveData ret;
		ret.width = width;
		ret.height = height;
		int size = ret.width * ret.height * 2;
		ret.data = new uchar[size];
		memcpy_s(ret.data, size, data, size);
		return ret;
	}
};

class CyDevice : public QObject {
	Q_OBJECT

public:
	CyDevice();
	~CyDevice();

	bool open(HANDLE hnd, int width = 2048, int height = 1);
	void close();
	void start();
	void stop();
	bool receiving();
	bool empty();
	void clear();
	ReceiveData read();

	enum TriggerType { Internal = 0, External};
	void setExposure(int exposure);
	void setTrigger(TriggerType trigger);

signals:	
	void received();

private:
	bool sendControlCode(int code);
	bool sendRequestCode(int code, QVector<uchar> buf);
	void enableReceive(bool enable);
	void receive();

	int height;
	int width;
	bool isReceiving;
	TriggerType triggerType;

	QQueue<ReceiveData> receiveQueue;
	
	QReadWriteLock mutex;

	CCyUSBDevice* device;
	CCyUSBEndPoint* dataInEndPoint;
	CCyControlEndPoint* controlEndPoint;
};

#endif